package server;

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

import java.net.*;
import java.io.*;
import java.util.Date;

public class Server {
    ServerSocket serverSocket;
    public static void main (String [] args ) { 
        try {
            // create socket 
                Server server = new Server();
                ServerSocket serverSocket= server._ConnectSocket(5217);
                System.out.println("Waiting for Connection on Port 5217...");
                while(true){
                    new ProcessFile(serverSocket.accept()).start();
                }
        } catch (IOException ex) {
        }                  
    }
    
    public ServerSocket _ConnectSocket(int port)
    {
        try {
            return new ServerSocket(port);
        } catch (IOException ex) {
        }
        return null;
    }
}


class ProcessFile extends Thread {
    protected Socket sock;
    protected DataInputStream in;
    protected DataOutputStream out;
    private BufferedOutputStream bos;
    public ProcessFile(Socket sock){
        try {
            this.sock = sock;
            out = new DataOutputStream(sock.getOutputStream());
            in = new DataInputStream(sock.getInputStream());
            System.out.println("Client "+sock.getInetAddress()+" is connecting");
        } catch (IOException ex) {
        }
    }
      
    @Override
      public void run() {
            //read file 
            this.ReceiveFile(sock);
      }
    
    
    public void ReceiveFile(Socket socket)
    {
        try {
            Date d = new Date();
            String fileName = "C:\\File\\"+d.getTime()+".khn";
            //Receive file
            byte [] bytearray  = new byte [1024*10];
            if(in.readUTF().compareTo("Fileinvalid")==0)
            {
                return;
            }

            FileOutputStream fos = new FileOutputStream(fileName);
            bos = new BufferedOutputStream(fos);
            
            int n=-1;
            int rn=0;
            long start = System.currentTimeMillis();
            while ((n = in.read(bytearray)) > -1){
                fos.write(bytearray, 0, n);
                rn+=n;
            }
            
            long end = System.currentTimeMillis();
            System.out.println("Receive successfuly "+(float)rn/1000 + " bytes written in " + (end-start)/1000 + " s.");
            
        } catch (IOException ex) {
        } finally {
            try {
                in.close();
                out.close();
                bos.flush();
                bos.close();
                System.out.println("Disconnect from: "+socket.getInetAddress()+"");
            } catch (IOException ex) {
            }
        }
    }
}
